/**
 * Created by sam on 16-10-13.
 */
var webpage = require('webpage'), page = webpage.create();
//var fs = require('fs');
var system =require('system');
//var keyword ='iphone 7 plus手机壳',wtype =0,psort =0;
//phantomjs ./crawl/jdRank.js 'iphone 7 plus手机壳' 0 0

page.viewportSize = { width: 1366, height: 720 };
page.settings = {
    javascriptEnabled: true,
    loadImages: false,
    webSecurityEnabled: false,
    userAgent: 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36 LBBROWSER'
};

page.onLoadStarted = function () {
    page.startTime = new Date();
};

var keyword = system.args[1],wtype = system.args[2],psort = system.args[3];
var index = system.args[4]||1;
var max = 10;
var pageNum = 10;
var timeOutMillis = 10000;
var url = "http://search.jd.com/Search?keyword="+encodeURIComponent(keyword)+"&enc=utf-8&wtype="+wtype+"&psort="+psort+"&page="+index;
//var url = "http://search.jd.com/Search?keyword=ipad+air2%E4%BF%9D%E6%8A%A4%E5%A5%97&enc=utf-8&wtype=0&psort=0";
page.open(url, function () {
    console.log('page start ----> keyword:'+keyword+', wtype:'+wtype+',psort:'+psort+',currPage:'+index);
    if (status === 'fail') {
        console.log('open page fail!');
    } else {
        waitFor(cb);
    }
});

function cb() {
       var p = page.evaluate(function () {
            $('.pn-next',$("#J_bottomPage")).click();
            return $(".p-skip >em >b",$("#J_bottomPage")).text();
        });
    pageNum = parseInt(p);
    if(pageNum<max){
        max = pageNum;
    }
    //console.log("indxe:"+index+" page:"+pageNum)
    if(max<=parseInt(index)){
        var t = Date.now() - page.startTime;
        console.log('time :' + (t/1000) + '秒');
        page.close();
        phantom.exit();
    }else{
        waitFor(cb);
        index++;

    }
}


//页面截图
function screan(filename) {
    page.render("../screan/"+filename);
}

function isReday() {
    return page.evaluate(function () {
        //判断页面加载完成的信号,
        window.scrollTo(0,9999);
        return $("#J_scroll_loading span").text()==''&&$("#J_loading").html()==null;
    });
}

function readData(callback) {
    page.evaluate(function (currPage) { //操作页面事件


        //var currPage = $("input",$("#J_bottomPage")).val();
        var key = $("#key").val();
        var psort =$(".f-sort .curr").text() =="销量"?3:0;
        var wtype = $('.selected',$("#J_feature")).text()=='京东配送'?1:0;
        var arr = [];
        $(".gl-item").each(function (i,e) {
            var obj = {};
            if($(e).attr("data-type")=='activity'){//活动
                var ad_title = $(".gl-act-title",$(e)).text();
                var ad_info = $(".gl-act-infor",$(e)).text();
                var name = ad_title+"#"+ad_info;
                var img = $(".gl-act-img img",$(e)).attr("src");
                if(img == undefined){
                    img = $(".gl-act-img img", $(e)).attr("data-lazy-img");
                }
                var url = $(".gl-act-img a",$(e)).attr("href");
                obj = {
                    name: name,
                    img: img,
                    shop: '',
                    sku: '',
                    price: 0,
                    commit: 0,
                    isZy: 0,
                    isAd: 1,
                    isActivity: 1,
                    url: url,
                    index: (i+1),
                    pageNum :currPage,
                    keyword:key,
                    psort:psort,
                    wtype:wtype
                };
            }else{
                var sku  = $(e).attr("data-sku");
                var spu  = $(e).attr("data-spu");
                var name = $(".p-name em", $(e)).first().text().trim();
                var img = $(".p-img img", $(e)).first().attr("src");
                if(img == undefined){
                    img = $(".p-img img", $(e)).first().attr("data-lazy-img");
                }
                var url = $(".p-img a",$(e)).first().attr("href");
                var commit = $(".p-commit a",$(e)).first().text().replace("+","");
                if(commit.indexOf('万')>0){
                    commit = parseFloat(commit)*10000;
                }
                var shop = $(".p-shop", $(e)).first().text();
                var price = $(".p-price strong>i", $(e)).first().text();
                var isZy = $(".p-icons img", $(e)).first().attr("data-tips")=='京东自营，品质保障'?1:0;
                var isAd = $(".p-promo-flag",$(e)).is("span")?1:0;
                obj = {
                    name: name,
                    img: img,
                    sku: sku,
                    shop: shop,
                    price: price,
                    commit: commit,
                    isZy: isZy,
                    isAd: isAd?1:0,
                    isActivity: 0,
                    url: url,
                    index: (i+1),
                    pageNum :currPage,
                    keyword:key,
                    psort:psort,
                    wtype:wtype
                };
            }
            arr.push(obj);
        });

        //把获得的数据提交保存
        //console.log(JSON.stringify({arr:arr}))
        jQuery.ajax({
            type: "POST",
            url:"http://127.0.0.1:1337/saveRank",
            dataType:"json",
            data:JSON.stringify({arr:arr}),
            async:false
        });

    },index);
    callback();
}

function waitFor(callback) {
    var start = new Date().getTime(),
        condition = false,
        interval = setInterval(function () {
            if ((new Date().getTime() - start < timeOutMillis) && !condition) {
                condition = isReday();
            } else {
                if (!condition) {

                    console.log("waitFor timeout|"+index);
                    page.close();
                    phantom.exit();
                } else {
                    console.log("waitFor page:"+index+" finished in " + (new Date().getTime() - start) + "ms.");
                    readData(callback);
                    clearInterval(interval);
                }
            }
        }, 250);
};

page.onConsoleMessage = function (msg) {
    console.log('CONSOLE:' + msg);
};
